package com.demo.user;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Model;

/**
 * Copyright 2014 李松泉 
 * 功能说明：TODO 
 * 开发时间：2014-1-10上午9:21:04
 * 开发作者：李松泉
 */
@SuppressWarnings("serial")
public class Resources extends Model<Resources>{
	public static final Resources dao = new Resources();
	//用户所拥有的权限Map，Key为Controller，Value为这个Controller下的Action的List
	public static Map<String, List<String>> antuMap = new HashMap<String, List<String>>();
	public static List<String> userActionKeyList = new ArrayList<String>();
	
	/**
	 * 获取当前用户的权限Map
	 * @param userId
	 * @return
	 */
	public static Map<String, List<String>> getAuthority(int userId) {
		Map<String, List<String>> thisAntuMap = new HashMap<String, List<String>>();
		List<String> controllerKeyList = new ArrayList<String>(); 
		String sql = "select t1.controller_key,t1.action_key from jf_demo_resources t1 where t1.id in(select t2.resources_id from jf_demo_role_resources t2 where t2.role_id in(select t3.user_id from jf_demo_user_role t3 where t3.user_id = "+userId+"))";
		List<Resources> resourcesList = dao.find(sql);
		
		for(Resources res : resourcesList){
			String controllerKey = res.getStr("controller_key");
			String actionKey = res.getStr("action_key");
			if(!controllerKeyList.contains(controllerKey))
				controllerKeyList.add(controllerKey);
			if(!userActionKeyList.contains(actionKey))
				userActionKeyList.add(actionKey);
		}
		
		for(String controllerKey : controllerKeyList){
			List<String> actionKeyList = new ArrayList<String>();
			for(Resources resTemp : resourcesList){
				String controllerKeyTemp = resTemp.getStr("controller_key");
				String actionKeyTemp = resTemp.getStr("action_key");
				if(controllerKeyTemp.equals(controllerKey) && !actionKeyList.contains(actionKeyTemp))
					actionKeyList.add(actionKeyTemp);
			}
			thisAntuMap.put(controllerKey, actionKeyList);
		}

		antuMap = thisAntuMap;
		return antuMap;
	}

	public static List<Resources> getAllResources() {
		return dao.find("select * from jf_demo_resources order by id asc");
	}
	
	/**
	 * 判断资源是否在数据库中配置了
	 * @param actionKey
	 * @return
	 */
	public static boolean isNeedAuthControl(String actionKey) {
		return dao.find("select * from jf_demo_resources where action_key = '"+actionKey+"'").size() > 0;
	}

	/**
	 * 根据角色id或许已绑定的资源id
	 * @param roleId
	 * @return
	 */
	public static List<Resources> getCheckedResources(int roleId) {
		return dao.find("select t1.resources_id from jf_demo_role_resources t1 where t1.role_id = " + roleId);
	}

	public static List<Resources> getResourcesList(Long roleId) {
		String sql = "select t1.id,t1.controller_key,t1.action_key from jf_demo_resources where t1.id in ("+"select t2.resources_id from jf_demo_role_resources t2 where t2.role_id = '"+roleId+"'"+")";
		return dao.find(sql);
	} 
}
